import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
import { GJDBFunction2 } from '@/utils/queryData'
import {
    dataTransFile,
} from "@/utils/api";
export default {
    install: async function (Vue, options) {

        Vue.prototype.getPdfto = function (ele, pdfFileName) {
          debugger
            ele = document.getElementById("pdfDom");
            pdfFileName = pdfFileName || "pdf";
            window.pageYoffset = 0; // 滚动置顶
            document.documentElement.scrollTop = 0;
            document.body.scrollTop = 0;
            // ele.style.fontSize = '18px'
            // ele.style.padding='30px';
            // let scale = window.devicePixelRatio * 2
            html2Canvas(ele, {
                // dpi: 300,
                dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
                scale: 4, // 按比例增加分辨率
                logging: false,
                // scale:scale,
                useCORS: true, // 允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
                allowTaint: false,
                height: ele.offsetHeight,
                width: ele.offsetWidth,
                windowWidth: document.body.scrollWidth,
                windowHeight: document.body.scrollHeight,
                backgroundColor: "#fff"
            }).then(async canvas => {
                // const _this = this
                // 未生成pdf的html页面高度
                var leftHeight = canvas.height;
                var a4Width = 555.28; // 原A4宽 592 因为要设置边距 20 ,这里要减掉 40
                var a4Height = 801.89; // 原A4高   841 因为要设置边距 20 ,这里要减掉 40
                // 一页pdf显示html页面生成的canvas高度;
                var a4HeightRef = Math.floor((canvas.width / a4Width) * a4Height);

                // pdf页面偏移
                var position = 0;

                var pageData = canvas.toDataURL("");
                var pdf = new JsPDF("x", "pt", "a4");
                // var index = 1
                const canvas1 = document.createElement("canvas");
                let height;
                pdf.setDisplayMode("fullwidth", "continuous", "FullScreen");
                let me = this;
                function createImpl (canvas) {
                    if (leftHeight > 0) {
                        // index ++
                        var checkCount = 0;
                        if (leftHeight > a4HeightRef) {
                            var i = position + a4HeightRef;
                            for (i = position + a4HeightRef; i >= position; i--) {
                                var isWrite = true;
                                for (var j = 0; j < canvas.width; j++) {
                                    var c = canvas.getContext("2d").getImageData(j, i, 1, 1).data;

                                    if (c[0] !== 0xff || c[1] !== 0xff || c[2] !== 0xff) {
                                        isWrite = false;
                                        break;
                                    }
                                }
                                if (isWrite) {
                                    checkCount++;
                                    if (checkCount >= 10) {
                                        break;
                                    }
                                } else {
                                    checkCount = 0;
                                }
                            }
                            height =
                                Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
                            if (height <= 0) {
                                height = a4HeightRef;
                            }
                        } else {
                            height = leftHeight;
                        }

                        canvas1.width = canvas.width;
                        canvas1.height = height;
                        var ctx = canvas1.getContext("2d");
                        ctx.drawImage(
                            canvas,
                            0,
                            position,
                            canvas.width,
                            height,
                            0,
                            0,
                            canvas.width,
                            height
                        ); // 边距这里设置0，不然又黑边
                        // var pageHeight = Math.round(a4Width / canvas.width * height)
                        // pdf.setPageSize(null, pageHeight)
                        if (position !== 0) {
                            pdf.addPage();
                        }
                        // 设置 20px 边距
                        pdf.addImage(
                            canvas1.toDataURL("image/jpeg", 1.0),
                            "JPEG",
                            20,
                            20,
                            a4Width,
                            (a4Width / canvas1.width) * height
                        );
                        leftHeight -= height;
                        position += height;
                        if (leftHeight > 0) {
                            // 添加全屏水印
                            /* const base64 = ''
                                          for (let i=0;i<6;i++) {
                                            for (let j=0;j<5;j++) {
                                              const  left = (j * 120) + 20
                                              pdf.addImage(base64,'JPEG', left, i*150, 20, 30); // 关掉水印
                                            }
                                          } */
                            setTimeout(createImpl, 0, canvas);
                        } else {
                            // pdf.save(pdfFileName + '.pdf')
                        }
                    }
                }
                if (leftHeight > 0) {
                    // var buffer = pdf.output("datauristring")
                    // 将base64格式的字符串转换为file文件
                    // var file = dataURLtoBlob(buffer)
                    pdf.addImage(
                        pageData,
                        "JPEG",
                        20,
                        20,
                        a4Width,
                        (a4Width / canvas.width) * leftHeight
                    );
                    // var buffer = pdf.output("datauristring")
                    // 将base64格式的字符串转换为file文件
                    // var file = dataURLtoBlob(buffer)
                    var myfile = dataURLtoFile(pageData, pdfFileName);
                    let DQHSJ = JSON.parse(window.sessionStorage.getItem('fileData'))
                    let data = {
                        toRowGuid: DQHSJ.ROW_GUID,
                        groupGuid: '6b824044-9162-476a-8d0a-85e0a09bff1c',
                        token: window.localStorage.getItem('token'),
                    }
                    let formData = new FormData()
                    formData.append('file', myfile)
                    formData.append('accessCode', '7a3fc061c866434b8475d3775c9ddcea')
                    formData.append(
                        'cityCode',
                        window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000'
                    )
                    formData.append('token', window.localStorage.getItem('token'))
                    formData.append('paramStr', JSON.stringify(data))
                    const res = await dataTransFile(formData)
                    let data1 = JSON.parse(res.data.data).FileList
                    this.fileGuid = data1[0].FILEGUID
                    debugger
                    //判断是pdf还是照片
                    if (data1[0].FILEGUID) {
                        this.$toast.success('上传成功!')
                        if (window.sessionStorage.getItem('ISBian') == 'true') {
                            const res = await GJDBFunction2('IN_NHZGFS', [{ beTASKID: JSON.parse(window.sessionStorage.getItem('fileData')).TASK_ID }])
                            if (res?.data == null) {
                              this.$toast.success('发送成功')
                              //重点 要清空一下 不然影响整个其他的流程
                              window.sessionStorage.removeItem('fileData')
                              this.$router.push({
                                path: '/ZLJIndex'
                            })
                            } else {
                              this.$toast.fail('发送失败')
                            }
                        } else {
                            setTimeout(() => {
                                this.$router.push({
                                    path: '/TreeSelect',
                                    query: {
                                        data: window.sessionStorage.getItem('fileData'),
                                        SJXK: 1,
                                    },
                                })
                            }, 500)
                        }
                    }
                }
                // 当内容未超过pdf一页显示的范围，无需分页
                if (leftHeight < a4HeightRef) {
                    // pdf.addImage(
                    //     pageData,
                    //     "JPEG",
                    //     20,
                    //     20,
                    //     a4Width,
                    //     (a4Width / canvas.width) * leftHeight
                    // );
                    // var buffer = pdf.output("datauristring")
                    // 将base64格式的字符串转换为file文件
                    // var file = dataURLtoBlob(buffer)
                    // var myfile = dataURLtoFile(pageData, pdfFileName);
                    // let DQHSJ = JSON.parse(window.sessionStorage.getItem('fileData'))
                    // let data = {
                    //     toRowGuid: DQHSJ.ROW_GUID,
                    //     groupGuid: '6b824044-9162-476a-8d0a-85e0a09bff1c',
                    //     token: window.localStorage.getItem('token'),
                    // }
                    // let formData = new FormData()
                    // formData.append('file', myfile)
                    // formData.append('accessCode', '7a3fc061c866434b8475d3775c9ddcea')
                    // formData.append(
                    //     'cityCode',
                    //     window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000'
                    // )
                    // formData.append('token', window.localStorage.getItem('token'))
                    // formData.append('paramStr', JSON.stringify(data))
                    // const res = await dataTransFile(formData)
                    // let data1 = JSON.parse(res.data.data).FileList
                    // this.fileGuid = data1[0].FILEGUID
                    debugger
                    //判断是pdf还是照片
                    // if (data1[0].FILEGUID) {
                    //     this.$toast.success('上传成功!')
                    //     if (window.sessionStorage.getItem('ISBian') == 'true') {
                    //         const res = await GJDBFunction2('IN_NHZGFS', [{ beTASKID: JSON.parse(window.sessionStorage.getItem('fileData')).TASK_ID }])
                    //         if (res?.data == null) {
                    //           this.$toast.success('发送成功')
                    //           //重点 要清空一下 不然影响整个其他的流程
                    //           window.sessionStorage.removeItem('fileData')
                    //         } else {
                    //           this.$toast.fail('发送失败')
                    //         }
                    //     } else {
                    //         setTimeout(() => {
                    //             this.$router.push({
                    //                 path: '/TreeSelect',
                    //                 query: {
                    //                     data: window.sessionStorage.getItem('fileData'),
                    //                     SJXK: 1,
                    //                 },
                    //             })
                    //         }, 500)
                    //     }
                    // }
                    // 发起请求

                } else {
                    try {
                        pdf.deletePage(0);
                        setTimeout(createImpl, 0, canvas);
                    } catch (err) { }
                }
            });
        };
    }
};

//将base64转换为文件对象
function dataURLtoFile (dataurl, filename) {
    var arr = dataurl.split(",");
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    //转换成file对象
    return new File([u8arr], filename, { type: mime });
    //转换成成blob对象
    //return new Blob([u8arr],{type:mime});
}
